package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.constant.MailConstants;
import com.xxxx.server.mapper.EmployeeMapper;
import com.xxxx.server.mapper.MailLogMapper;
import com.xxxx.server.pojo.Employee;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IEmployeeService;
import com.xxxx.server.util.RespBean;
import com.xxxx.server.util.RespPageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyd
 * @since 2023-06-11
 */
@Service
@Slf4j(topic = "EmployeeServiceImpl")
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;

    /**
     * 分页得到员工数据
     * @param currentPage
     * @param pageSize
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public RespPageBean getEmpByPage(Integer currentPage, Integer pageSize, Employee employee, LocalDate[] beginDateScope) {

        Page<Employee> page = new Page<>(currentPage,pageSize);

        IPage<Employee> employeeIPage =  employeeMapper.getEmpByPage(page,employee,beginDateScope);

        RespPageBean respPageBean = new RespPageBean(employeeIPage.getTotal(),employeeIPage.getRecords());

        return respPageBean;
    }

    /**
     * 获取工号
     * @return
     */
    @Override
    public RespBean maxWorkedId() {

        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));

        log.info("获取工号1 maxWorkedId:{}",maps );

        log.info("获取工号2 maxWorkedId:{}",maps.get(0).get("max(workID)"));

        log.info("获取工号3 maxWorkedId:{}",Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1) ;

        String format = String.format("缺位补零：%08d", 101);

        System.out.println("format = " + format);

        return RespBean.success("生成工号",String.format("生成工号：%08d",Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1));
    }

    @Override
    public RespBean addEmp(Employee employee) {

        //处理合同期限，保留两位小数
        LocalDate beginContract = employee.getBeginContract();

        LocalDate endContract = employee.getEndContract();

        long days = beginContract.until(endContract, ChronoUnit.DAYS);

        DecimalFormat decimalFormat = new DecimalFormat("##.00");

        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));

        if (1 == employeeMapper.insert(employee)){

            Employee emp = employeeMapper.getEmployeeExcel(employee.getId()).get(0);

            //消息ID -- 数据库记录发送的消息
            String msgID = UUID.randomUUID().toString();

            MailLog mailLog = new MailLog();

            mailLog.setMsgId(msgID);
            mailLog.setEid(employee.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setCount(0);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            //重试时间 -- 当前时间 + 1分钟
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());

            mailLogMapper.insert(mailLog);

            // 使用rabbitmq发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,emp,new CorrelationData(msgID));

            return RespBean.success("添加员工成功！");
        }
        return RespBean.error("添加员工失败！");
    }

    @Override
    public List<Employee> getEmployeeExcel(Integer id) {


        return employeeMapper.getEmployeeExcel(id);
    }
}
